package com.sport.common.word;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.jeesite.common.codec.EncodeUtils;
import com.sport.common.excel.ExcelExport;
import com.sport.model.excel.SportMemberEnrollExport;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Response;
import org.apache.poi.ss.formula.functions.T;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class WordExport {
    /**
     * 根据本地文件流生成word
     *
     */
    public  void generateByFile(Map<Map<String,String>,List<List<SportMemberEnrollExport>> > memberListMap,HttpServletResponse response,String fileName) throws IOException {
        //创建一个临时文件夹来保存生成的临时文件
        File tempFolder=createTempFolder();
        for (Map.Entry<Map<String, String>, List<List<SportMemberEnrollExport>> > mapListEntry : memberListMap.entrySet()) {
            Map<String, String> titleMap = mapListEntry.getKey();
            List<List<SportMemberEnrollExport>>  memberList = mapListEntry.getValue();
            generateTemplate(memberList, titleMap, tempFolder);
        }
        //合并临时文件
        mergeTempFiles(tempFolder, response, fileName);
//        //输出文件到客户端
//        write(render,response,fileName);
    }

    public void mergeTempFiles(File tempFolder, HttpServletResponse response, String fileName) {
        try {
        File[] files = tempFolder.listFiles();
        if(files!=null&&files.length>0) {
            response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8");
            response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'" + EncodeUtils.encodeUrl(fileName));

            ServletOutputStream outputStream = response.getOutputStream();
            FileInputStream fis;
            byte[] buffer= new byte[4096];
            int bytesRead;
            for (File file : files) {
                fis=new FileInputStream(file);
                while((bytesRead=fis.read(buffer))!=-1){
                    outputStream.write(buffer,0,bytesRead);
                }
                fis.close();
            }
            outputStream.flush();
            outputStream.close();

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    private  void generateTemplate(List<List<SportMemberEnrollExport>> memberList, Map<String, String> titleMap,File tempFolder) throws IOException {
        Map<String,Object> finallyMap=new HashMap<>();
        List<Object> showMaleList=new ArrayList<>();
        List<Object> showFemaleList=new ArrayList<>();
        finallyMap.put("比赛组", titleMap.get("比赛组"));
        finallyMap.put("比赛单位", titleMap.get("比赛单位"));
//        finallyMap.put("比赛组","二年级");
//        finallyMap.put("比赛单位","2班");


        addData(memberList.get(0), showMaleList);
        finallyMap.put("参赛成员列表1",showMaleList);
        addData(memberList.get(1),showFemaleList);
        finallyMap.put("参赛成员列表2",showFemaleList);
        // 从网络url 下载word模板到指定文件夹
        File wordTemplate = new File("/docker/java/word/word模板.docx");
        // 此处使用了poi-tl的<表格行循环插件>，此处一定要进行参数bind，方便word模板参数替换
        LoopRowTableRenderPolicy policy1 = new LoopRowTableRenderPolicy();
        LoopRowTableRenderPolicy policy2 = new LoopRowTableRenderPolicy();
        Configure build = Configure.builder().bind(policy1, "参赛成员列表1")
                                             .bind(policy2,"参赛成员列表2")
                                             .build();
        // 进行编译
        //形成临时文件路径
        String tempFilePath=tempFolder.getAbsolutePath()+File.separator+"filled_document.docx";
        String absolutePath = wordTemplate.getAbsolutePath();
        System.out.println(absolutePath + " " + tempFilePath);
        XWPFTemplate render = XWPFTemplate.compile(absolutePath, build).render(finallyMap);
        //保存到临时文件
        render.writeToFile(tempFilePath);

        render.close();

    }

    private static void addData(List<SportMemberEnrollExport> memberList, List<Object> showList) {
        for (SportMemberEnrollExport sportMemberEnrollExport : memberList) {
            Map<String,Object> memberMap=new HashMap<>();
            memberMap.put("号码",sportMemberEnrollExport.getSportMemberNum());
            memberMap.put("姓名",sportMemberEnrollExport.getSportMemberName());
            memberMap.put("项目1",sportMemberEnrollExport.getSportMemberProject1());
            memberMap.put("项目2",sportMemberEnrollExport.getSportMemberProject2());
            memberMap.put("项目3",sportMemberEnrollExport.getSportMemberProject3());
            memberMap.put("项目4",sportMemberEnrollExport.getSportMemberProject4());
            memberMap.put("项目5",sportMemberEnrollExport.getSportMemberProject5());
            showList.add(memberMap);
        }
    }

    public File createTempFolder() {
        String tempFoldPath = System.getProperty("java.io.tmpddir");
        File tempFolder = new File(tempFoldPath, "word-export");
        if(!tempFolder.exists()){
            tempFolder.mkdirs();
        }
        return tempFolder;
    }

//    /**
//     * 输出到客户端
//     * @param fileName 输出文件名
//     */
//    public void write(XWPFTemplate render,HttpServletResponse response, String fileName){
//        response.reset();
//        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document; charset=utf-8");
//        response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+ EncodeUtils.encodeUrl(fileName));
//        try {
//            render.write(response.getOutputStream());
//        } catch (IOException ex) {
//            log.error(ex.getMessage(), ex);
//        }
//    }

//    public static void main(String[] args) throws IOException {
//        List<SportMemberEnrollExport> list =new ArrayList<>();
//        List<SportMemberEnrollExport> list1 =new ArrayList<>();
//        Map<Map<String,String>,List<SportMemberEnrollExport>> memberListMap=new HashMap<>();
//        Map<String,String> titleMap1=new HashMap<>();
//        Map<String,String> titleMap2=new HashMap<>();
//        titleMap1.put("比赛组","一年级");
//        titleMap1.put("比赛单位","一年级(1)班");
//        titleMap2.put("比赛组","一年级");
//        titleMap2.put("比赛单位","一年级(2)班");
//
//            SportMemberEnrollExport sportMemberEnrollExport = new SportMemberEnrollExport();
//            sportMemberEnrollExport.setSportMemberNum("123");
//            sportMemberEnrollExport.setSportMemberName("张三");
//            sportMemberEnrollExport.setSportMemberGender("男");
//            sportMemberEnrollExport.setSportMemberProject1("100米直跑");
//            sportMemberEnrollExport.setSportMemberProject2("110跨栏");
//            sportMemberEnrollExport.setSportMemberProject3("110跨栏");
//            sportMemberEnrollExport.setSportMemberProject4("110跨栏");
//            sportMemberEnrollExport.setSportMemberProject5("110跨栏");
//            list.add(sportMemberEnrollExport);
//            list1.add(sportMemberEnrollExport);
//            memberListMap.put(titleMap1,list);
//            memberListMap.put(titleMap2,list1);
//            String fileName="测试";
//        WordExport wordExport = new WordExport();
//        wordExport.generateByFile(memberListMap,new Response(),fileName);
//    }
}
